import { loginApi, getInfoApi, loginOutApi } from '@/api/user'

const state = () => ({
  token: '', // 登录token
  info: {} // 用户信息
})

// getters
const getters = {
  token(state) {
    return state.token
  }
}

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token
  },
  infoChange(state, info) {
    state.info = info
  }
}

// actions
const actions = {
  // login by login.vue
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      // loginApi(params).then((res) => {
      //   commit('tokenChange', res.data.token)
      dispatch('getInfo', { token: 'admin' }).then(infoRes => {
        resolve('admin')
      })
      commit('tokenChange', 'admin')
      resolve('admin')
      // })
    })
  },

  // get user info after user logined
  getInfo({ commit }, params) {
    return new Promise((resolve, reject) => {
      // getInfoApi(params).then((res) => {
      commit('infoChange', {
        name: '系统管理员'
      })
      resolve({
        name: '系统管理员'
      })
      // })
    })
  },

  // login out the system after user click the loginOut button
  loginOut({ commit }) {
    localStorage.removeItem('tabs')
    localStorage.removeItem('vuex')
    location.reload()
  }
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}
